// pages/draw/draw.js
var app = getApp();
const getPageInfoUrl = '/Draw/index';
const getDrawListUrl = '/Draw/helpList';
const getRuleUrl = '/draw/rule';
const shareSuccessUrl = '/Bargain/shareSuccess';
const helpCutPriceUrl = '/Bargain/helpBargain';
const drawLuckCodeUrl = '/Draw/drawLuckCode';
const drawDetailUrl = '/Draw/drawDetail';
const getLuckyCodeListUrl = '/Draw/luckyCodeList';
const getRankListUrl = '/Draw/luckyCodeRank';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    total_num:'',//剩余件数
    draw_num:'',//每天抽取件数
    rankList:[],//幸运码排行榜列表
    isRankingShow:0,//控制幸运码排行榜弹层的显示
    isLuckyCodeShow:0,//控制我的幸运码弹层的显示
    luckyCodeList:[],//我的幸运码列表
    current:0,//抽奖详情弹层当前显示的页面
    isDrawDeatailShow:0,//控制抽奖详情弹层的显示
    drawDetailList:[[1,2,3],[1,2]],//中奖详情列表
    help_num: 0, //1弹分享层 0不弹层 
    rank: '', //排名
    lucky_code_num: '', //幸运码个数
    get_lucky_code_btn_title: '', //“领取1张幸运码，获得中奖资格”按钮文案
    lottery_time: '', //开奖时间
    displayAuthShow: 0, //控制授权弹层的显示和隐藏
    user_nick: '', //用户昵称
    user_image: '', //用户头像
    service_bargain_detail_is_show: 0, //客服ico是否显示
    service_content: '', //客服描述
    service_reply_btn_title: '', //客服按钮文案
    is_kf_mask_show: 0, //控制客服弹层的显示
    is_godsign_show: 1, //是否显示使用神签按钮
    isLoading: 0, //是否显示加载中
    user_level: 0, //用户的身份
    is_not_enough: 0, //判断神签数量是否足够
    godsign_num: 0, //神签数
    // guide: {}, //引导盒子文案
    adv_info: [], //页面顶部专题列表
    static_url_http: '', //资源文件地址
    // is_bargain:0,//判断是否为砍价商品
    recommendList: [], //商品推荐列表
    page: 1, //商品推荐页码
    luckyCodePage:1,//幸运码列表页码
    goodsId: 0, //商品ID
    cash: {}, //赠送给好友的优惠券信息
    self_share_num: '', //自己给自己分享的次数
    is_group: 0, //判断分享的是否为群
    encryptedData: '', //分享的参数
    iv: '', //分享的参数
    shareTitle: '', //分享的标题
    sharePath: '', //分享的路径
    shareImg: '', //分享的图片
    ruleList: [], //规则列表
    countDownDay: '00', //倒计时的天数
    countDownHour: '00', //倒计时的小时数
    countDownMinute: '00', //倒计时的分钟数
    countDownSecond: '00', //倒计时的秒数
    helpList: [], //砍价榜列表
    helpListPage: 1, //砍价榜页面
    user_avatar: '', //用户头像地址
    user_nick: '', //用户昵称
    goods_img: '', //商品图片
    goods_name: '', //商品标题
    draw_suceess_title: '', //"您已成功帮TA助力"文案
    bargain_help_btn_title: '', //好友进入页面按钮文案
    share_btn_title: '', //喊好友助力
    share_group_one_title: '', //“每个好友可帮忙助力一个幸运码”文案
    share_group_two_title: '',//“幸运码越多越容易中奖，”文案
    share_group_three_title: '',//“分享到3个群，将提高90%中奖率”文案
    share_group_btn_title: '', //“分享到群，继续抽码”文案
    thank_help_title: '',//“谢谢帮我领取了一个幸运码”文案
    get_goods_title: '',//“赶紧也去1分拿好物吧，快被抢光喽”文案
    join_vip_title: '', //加入会员文案
    godsign_random_title: '', //“将随机获得50-500个神签”文案
    lucky_detail_title: '', //“查看中奖详情”文案
    help_god_sign_btn_title: '',//“使用神签再帮TA领一张”文案
    get_goods_btn_title: '', //“我也要0元拿好物”按钮文案
    filtration_title: '',//“少量异常用户将会被过滤”文案
    get_lucky_code_title:'',//“获取更多幸运码”文案
    show_rank_title: '',//“只展现前20名的排名”文案
    help_get_code_title: '',//“助力获取更多幸运码”文案
    god_sign_btn_title:'', //“使用神签抽一张”文案
    godsign_nonum_title: '',//“神签数量不足”文案
    godsign_nonum_novip_btn_title: '',//“加入会员领神签”文案
    godsign_nonum_vip_btn_title: '',//“快去邀请好友帮忙助力领取吧”文案
    end_time: '', //订单结束的时间戳
    is_end: 0, //判断是否已经结束
    scheduleWidth: 0, //进度条宽度
    order_id: 0, //订单ID
    share_uid: 0, //分享者ID
    isfriendCutMaskShow: 0, //控制好友砍价成功弹层的显示
    isSelfCutMaskShow: 0, //控制自己砍价成功弹层的显示
    isResultMaskShow: 0, //控制规则弹层的显示
    winWidth: 0, //手机屏幕的宽度
    winHeight: 0, //手机屏幕的高度
  },
  // 获取幸运码排行榜
  getRankList: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
      page: 1
    }
    app.post(getRankListUrl, requestData, function (res) {
      var rankList = res.data.list;
      for (var i = 0; i < rankList.length;i++){
        var num = Math.floor(rankList[i].user_nick.length / 2);
        rankList[i].user_nick = rankList[i].user_nick.replace(/\s*/g, "").substr(num-1, 2);
      }
      if (res.code == 2000) {
        _this.setData({
          rankList: rankList,
          isRankingShow: 1
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 获取我的幸运码列表
  getLuckyCodeList: function (e) {
    var _this = this;
    console.log(e);
    // if (e.currentTarget.dataset.page==1){
    //   _this.setData({
    //     luckyCodePage: e.currentTarget.dataset.page
    //   })
    // }
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
      page: _this.data.luckyCodePage
    }
    app.post(getLuckyCodeListUrl, requestData, function (res) {
      // var 
      if (res.code == 2000) {
        var luckyCodeList = _this.data.luckyCodeList;
        luckyCodeList = luckyCodeList.concat(res.data.list);
        _this.setData({
          lucky_code_num: luckyCodeList.length,
          luckyCodeList: luckyCodeList,
          filtration_title: res.data.filtration_title,
          get_lucky_code_title: res.data.get_lucky_code_title,
          luckyCodePage:res.data.page,
          isLuckyCodeShow: 1
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  changeCurrent:function(e){
    this.setData({
      current:e.currentTarget.dataset.current
    })
  },
  // 查看中奖详情
  viewDrawDetail: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
    }
    app.post(drawDetailUrl, requestData, function (res) {
      if (res.code == 2000) {
        var drawDetailList = res.data.list;
        for (var i = 0; i < drawDetailList.length; i++) {
          var num = Math.floor(drawDetailList[i].user_nick.length / 2);
          drawDetailList[i].user_nick = drawDetailList[i].user_nick.replace(/\s*/g, "").substr(num - 1, 2);
        }
       _this.setData({
         drawDetailList: drawDetailList,
         isDrawDeatailShow:1
       })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 打开客服弹层
  openKfmask: function() {
    this.setData({
      is_kf_mask_show: 1
    });
  },
  // 抽取幸运码
  drawLuckCode: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    if (_this.data.godsign_num == 0 && _this.data.lucky_code_num!=0) {
      _this.setData({
        isSelfCutMaskShow: 1,
        is_not_enough: 1
      })
    } else {
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
      uid: _this.data.share_uid,
      is_godsign: e.target.dataset.is_godsign
    }
    app.post(drawLuckCodeUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          lucky_code_num: res.data.lucky_code_num,
          godsign_num:res.data.num,
          rank: res.data.rank,
          user_level: res.data.level,
          isSelfCutMaskShow: 1
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
    }
  },
  // 判断是否为空对象
  isEmptyObject: function(obj) {
    for (var key in obj) {
      return true
    };
    return false
  },
  // 跳转会员页
  goVip: function(e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    wx.navigateTo({
      url: '/pages/vipRecharge/vipRecharge',
    })
  },
  // 点击顶部导航跳转广告详情
  jumpDetail: function(e) {
    var advType = e.currentTarget.dataset.type_detail;
    console.log(advType);
    if (advType.adv_type == 3) {
      wx.navigateToMiniProgram({
        appId: advType.app_id.toString(),
        path: advType.page.toString(),
        extraData: advType.sence.toString(),
        complete(res) {
          console.log(res)
        }
      });
    } else if (advType.adv_type == 4) {
      var subject_id = advType.adv_id;
      wx.navigateTo({
        url: '/' + advType.adv_uri + '?subject_id=' + subject_id,
      })
    }
  },
  // 跳转我的现金券页面
  goCouponList: function() {
    wx.navigateTo({
      url: '/pages/couponList/couponList',
    })
  },
  // 跳转商品详情页
  goGoodsDetail: function(e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    console.log(e);
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + e.currentTarget.dataset.goods_id,
    })
  },
  // 跳转订单详情页
  goOrderDetail: function(e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?orderId=' + this.data.order_id,
    })
  },
  // 获取页面信息
  getPageInfo: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
      uid: _this.data.share_uid
    }
    app.post(getPageInfoUrl, requestData, function(res) {
      if (res.code == 2000) {
        var configs = wx.getStorageSync('configs');
        // 开奖时间
        var end_time = res.data.end_time;
        var lottery_time = _this.formatDate('Y年m月d日 H:i', end_time);
        _this.setData({
          total_num: res.data.total_num,
          draw_num: res.data.draw_num,
          show_rank_title: res.data.show_rank_title,
          godsign_nonum_title: res.data.godsign_nonum_title,
        godsign_nonum_vip_btn_title: res.data.godsign_nonum_vip_btn_title,
          help_god_sign_btn_title: res.data.help_god_sign_btn_title,
          god_sign_btn_title: res.data.god_sign_btn_title,
          help_get_code_title: res.data.help_get_code_title,
          lucky_code_num: res.data.lucky_code_num,
          rank: res.data.rank,
          get_lucky_code_btn_title: res.data.get_lucky_code_btn_title,
          get_goods_title:res.data.get_goods_title,
          user_nick: res.data.user_nick,
          help_num: res.data.help_num,
          lottery_time: lottery_time,
          user_image: res.data.image,
          thank_help_title: res.data.thank_help_title,
          service_bargain_detail_is_show: configs.service_bargain_detail_is_show,
          lucky_detail_title: res.data.lucky_detail_title,
          service_content: configs.service_content,
          service_reply_btn_title: configs.service_reply_btn_title,
          isLoading: 0,
          user_level: res.data.level,
          godsign_num: res.data.godsign_num,
          // adv_solt: res.data.adv,
          user_nick: res.data.user_nick,
          user_avatar: res.data.image,
          goods_img: configs.static_url_http + '/' + res.data.goods_img,
          join_vip_title: res.data.join_vip_title,
          godsign_random_title: res.data.godsign_random_title,
          goods_name: res.data.goods_name,
          get_goods_btn_title: res.data.get_goods_btn_title,
          share_btn_title: res.data.share_btn_title,
          draw_suceess_title: res.data.draw_suceess_title,
          is_godsign_show: res.data.is_godsign_show,
          is_self: res.data.is_self,
          end_time: res.data.end_time,
          is_end: res.data.is_end,
          share_group_one_title: res.data.share_group_one_title,
          share_group_two_title: res.data.share_group_two_title,
          share_group_three_title: res.data.share_group_three_title,
          share_group_btn_title: res.data.share_group_btn_title,
          shareTitle: res.data.share.title,
          sharePath: res.data.share.page,
          shareImg: res.data.share.image,
          share_uid: res.data.uid,
          order_id: res.data.order_id,
          goodsId: res.data.goods_id
        })
        _this.getDrawList();
        _this.getRecommendList();
        if (res.data.is_end == 0) {
          _this.bargainCountDown();

          if (res.data.help_num == 1) {
            if (res.data.is_self == 1) {
              _this.setData({
                isSelfCutMaskShow: 1
              })
            } else {

              _this.setData({
                isfriendCutMaskShow: 1
              })
            }
          }
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 获取助力榜信息
  getDrawList: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      uid: _this.data.share_uid,
      order_id: _this.data.order_id
    }
    app.post(getDrawListUrl, requestData, function(res) {
      if (res.code == 2000) {
        var helpList = res.data.list;
        var helpListHeight;
        if (helpList.length < 2) {
          helpListHeight = 'auto'
        } else {
          helpListHeight = '240rpx';
        }
        _this.setData({
          helpListHeight: helpListHeight,
          helpList: helpList
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 获取砍价规则
  getRule: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
    }
    app.post(getRuleUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          ruleList: res.data.rule_list
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 获取商品推荐列表
  getRecommendList: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      keywords: _this.data.goods_name,
      recommend_type: 3,
      search_type: 0,
      page: _this.data.page
    }
    app.post('/Goods/recommend', requestData, function(res) {
      if (res.code == 2000) {
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
        var recommendList = _this.data.recommendList;
        var configs = wx.getStorageSync('configs');
        for (var i = 0; i < res.data.list.length; i++) {
          res.data.list[i].img = configs.static_url_http + '/' + res.data.list[i].img;
        }
        recommendList = recommendList.concat(res.data.list);
        _this.setData({
          static_url_http: configs.static_url_http,
          page: res.data.page,
          recommendList: recommendList
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 关闭幸运码排行榜弹层
  closeRankMask: function () {
    this.setData({
      isRankingShow: 0
    })
  },
  // 关闭中奖详情弹层
  closeDrawDeatail: function () {
    this.setData({
      isDrawDeatailShow: 0
    })
  },
  // 关闭我的幸运码弹层
  closeluckyCodeMask: function () {
    this.setData({
      isLuckyCodeShow: 0
    })
  },
  // 关闭客服弹层
  closeKfmask: function () {
    this.setData({
      is_kf_mask_show: 0
    });
  },
  // 关闭好友砍价成功的弹层
  closefriendCutMask: function() {
    var _this = this;
    _this.setData({
      isfriendCutMaskShow: 0
    });
  },
  // 关闭自己砍价成功的弹层
  closeSelfCutMask: function() {
    var _this = this;
    // console.log("点");
    _this.setData({
      isSelfCutMaskShow: 0
    });

  },
  // 关闭规则弹层
  closeRuleMask: function() {
    var _this = this;
    _this.setData({
      isResultMaskShow: 0
    });
  },
  ruleEntrance: function() {
    var _this = this;
    _this.setData({
      isResultMaskShow: 1
    });
  },
  /*红包广告跳转事件*/
  goAdvEvent: function(e) {
    var _this = this;
    // var adv_solt = _this.data.adv_solt;
    if (_this.data.adv_solt) {
      //广告数据不为空
      if (adv_solt.adv_type == 1) {
        //图片类
        wx.navigateTo({
          url: '/pages/rule/rule?url=' + adv_solt.adv_info_url
        });
      } else if (adv_solt.adv_type == 3) {
        //小程序类
        wx.navigateToMiniProgram({
          appId: adv_solt.app_id.toString(),
          path: adv_solt.page.toString(),
          extraData: adv_solt.sence.toString(),
          complete(res) {}
        });
      } else {
        //内部网页类型
        wx.navigateTo({
          url: "/" + adv_solt.adv_uri,
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        })
      }
    });
    _this.setData({
      order_id: options.order_id
    })
    if (options.uid) {
      _this.setData({
        share_uid: options.uid
      })
    }
    app.checkAuthioze(success => {
      _this.loop();
    }, fail => {
      //未授权提示用户授权
      _this.setData({
        displayAuthShow: 1
      });
    });
  },
  // 判断是否获取到token的值了
  loop: function() {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    var theRegionUnit = _this.data.regionUnit;
    if (!theToken) {
      setTimeout(function() {
        _this.loop()
      }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      _this.getPageInfo();
      _this.getRule();
      _this.getRecommendList();
    }
  },
  /*角色权限控制*/
  getUserInfo: function(e) {
    var that = this;
    var infoUser = e.detail.userInfo;
    var res = e.detail;
    var url = app.setConfig.url + '/Login/doLogin';
    that.setData({
      displayAuthShow: 0,
      isGetInfo: 1
    });
    var data = {
      user_name: infoUser.nickName,
      nick_name: infoUser.nickName,
      head_img: infoUser.avatarUrl,
      sex: infoUser.gender,
      coutry: infoUser.country,
      city: infoUser.city,
      province: infoUser.province,
      code: app.globalData.code,
      encryptedData: res.encryptedData,
      signature: res.signature,
      ctype: app.setConfig.type,
      version: app.setConfig.version,
      iv: res.iv,
    }
    app.postLogin(url, data, function() {
      var cash = wx.getStorageSync('cash');
      if (cash != "") {
        that.setData({
          displayAuthShow: 0,
          cash: cash
        })
      }
      that.loop();
      wx.navigateBack({
        delta: 1,
      })
    });
  },
  authRest: function() {
    this.setData({
      displayAuthShow: 0
    });
    setTimeout(function() {
      wx.reLaunch({
        url: '/pages/bargain/bargain',
      })
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.showShareMenu({
      withShareTicket: true,
      success: function(res) {
        console.log('参数', res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    var _this = this;
    _this.setData({
      isfriendCutMaskShow: 0, //控制好友砍价成功弹层的显示
      isSelfCutMaskShow: 0, //控制自己砍价成功弹层的显示
      isResultMaskShow: 0, //控制规则弹层的显示
    })
    return {
      title: _this.data.shareTitle,
      path: _this.data.sharePath,
      imageUrl: _this.data.shareImg,
      success: function(res) {}

    }

  },
  // 帮助好友砍价
  helpCutPrice: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
      uid: _this.data.share_uid
    }
    app.post(helpCutPriceUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          other_bargain_money: res.data.other_bargain_money,
          isfriendCutMaskShow: 1
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 倒计时
  bargainCountDown: function() {
    var _this = this;
    var end_time = _this.data.end_time;
    var totalSecond = end_time - Date.parse(new Date()) / 1000;

    var interval = setInterval(function() {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        _this.setData({
          auction_status: 2
        })
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
        });
      }
    }.bind(this), 1000);
  },
// 格式化时间
  formatDate: function(format, timestamp) {
    var a, jsdate = ((timestamp) ? new Date(timestamp * 1000) : new Date());
    var pad = function(n, c) {
      if ((n = n + "").length < c) {
        return new Array(++c - n.length).join("0") + n;
      } else {
        return n;
      }
    };
    var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var txt_ordin = {
      1: "st",
      2: "nd",
      3: "rd",
      21: "st",
      22: "nd",
      23: "rd",
      31: "st"
    };
    var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var f = {
      // Day 
      d: function() {
        return pad(f.j(), 2)
      },
      D: function() {
        return f.l().substr(0, 3)
      },
      j: function() {
        return jsdate.getDate()
      },
      l: function() {
        return txt_weekdays[f.w()]
      },
      N: function() {
        return f.w() + 1
      },
      S: function() {
        return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'
      },
      w: function() {
        return jsdate.getDay()
      },
      z: function() {
        return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0
      },

      // Week 
      W: function() {
        var a = f.z(),
          b = 364 + f.L() - a;
        var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
        if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b) {
          return 1;
        } else {
          if (a <= 2 && nd >= 4 && a >= (6 - nd)) {
            nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
            return date("W", Math.round(nd2.getTime() / 1000));
          } else {
            return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
          }
        }
      },

      // Month 
      F: function() {
        return txt_months[f.n()]
      },
      m: function() {
        return pad(f.n(), 2)
      },
      M: function() {
        return f.F().substr(0, 3)
      },
      n: function() {
        return jsdate.getMonth() + 1
      },
      t: function() {
        var n;
        if ((n = jsdate.getMonth() + 1) == 2) {
          return 28 + f.L();
        } else {
          if (n & 1 && n < 8 || !(n & 1) && n > 7) {
            return 31;
          } else {
            return 30;
          }
        }
      },

      // Year 
      L: function() {
        var y = f.Y();
        return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0
      },
      //o not supported yet 
      Y: function() {
        return jsdate.getFullYear()
      },
      y: function() {
        return (jsdate.getFullYear() + "").slice(2)
      },

      // Time 
      a: function() {
        return jsdate.getHours() > 11 ? "pm" : "am"
      },
      A: function() {
        return f.a().toUpperCase()
      },
      B: function() {
        // peter paul koch: 
        var off = (jsdate.getTimezoneOffset() + 60) * 60;
        var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
        var beat = Math.floor(theSeconds / 86.4);
        if (beat > 1000) beat -= 1000;
        if (beat < 0) beat += 1000;
        if ((String(beat)).length == 1) beat = "00" + beat;
        if ((String(beat)).length == 2) beat = "0" + beat;
        return beat;
      },
      g: function() {
        return jsdate.getHours() % 12 || 12
      },
      G: function() {
        return jsdate.getHours()
      },
      h: function() {
        return pad(f.g(), 2)
      },
      H: function() {
        return pad(jsdate.getHours(), 2)
      },
      i: function() {
        return pad(jsdate.getMinutes(), 2)
      },
      s: function() {
        return pad(jsdate.getSeconds(), 2)
      },
      //u not supported yet 

      // Timezone 
      //e not supported yet 
      //I not supported yet 
      O: function() {
        var t = pad(Math.abs(jsdate.getTimezoneOffset() / 60 * 100), 4);
        if (jsdate.getTimezoneOffset() > 0) t = "-" + t;
        else t = "+" + t;
        return t;
      },
      P: function() {
        var O = f.O();
        return (O.substr(0, 3) + ":" + O.substr(3, 2))
      },
      //T not supported yet 
      //Z not supported yet 

      // Full Date/Time 
      c: function() {
        return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()
      },
      //r not supported yet 
      U: function() {
        return Math.round(jsdate.getTime() / 1000)
      }
    };
    var ret;
    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s) {
      if (t != s) {
        // escaped 
        ret = s;
      } else if (f[s]) {
        // a date function exists 
        ret = f[s]();
      } else {
        // nothing special 
        ret = s;
      }
      return ret;
    });
  }
})